<template>
  <div>
    <el-container>
      <el-header height="auto">
        <el-carousel height="300px" arrow="never">
          <el-carousel-item v-for="item in banners" :key="item">
            <img :src="picurl+item.pic_url" alt="" class="banner">
          </el-carousel-item>
        </el-carousel>
      </el-header>
      <el-main>
        <el-row type="flex" :gutter="24" style="align-items: center">
          <el-col :span="5">
            <div>{{location.city}}</div>
          </el-col>
          <el-col :span="15">
            <el-input
              v-model="keyWords"
              value=""
              class="search"
              placeholder="输入地址"
              prefix-icon="el-icon-search">
            </el-input>
          </el-col>
          <el-col :span='4'>
            <div @click="getShops"> 搜索</div>
          </el-col>
        </el-row>
        <el-row :gutter="8">
          <div class="rebtn" @click="getLocation"><i class="iconfont icon_posit"></i>重新定位</div>
        </el-row>
        <el-row :gutter="8" v-for="item in shopList">
          <div class="store" @click="goShop(item)">
            <div class="name">
              <span>{{item.name}}</span>
              <!--<span>153km</span>-->
            </div>
            <div class="time">营业时间：{{item.opened_at}}:00-{{item.closed_at}}:00</div>
            <div class="address">{{item.address}}</div>
          </div>
        </el-row>
        <el-row>
          <router-view></router-view>
        </el-row>
      </el-main>
    </el-container>

  </div>
</template>

<script>
  import {_post} from '@/api/mainApi';

  export default {
    name: 'Index',
    data() {
      return {
        applet_id: 1,
        shopList: [],
        keyWords: '',
        location: {city: ''},
        banners: [],
        picurl: this.GLOBAL.picurl,
        redirect_uri: encodeURIComponent(this.GLOBAL.webUrl)
      };
    },
    computed: {},
    created: function () {
      if (this.getQuery('applet_id')) {
        this.$cookies.set('applet_id', this.getQuery('applet_id'));
      }
      if (window.location.href.indexOf('code') === -1) {
        window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc11d0078737dab8b&redirect_uri=${this.redirect_uri}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`;
        return false;
      }
      const domine = window.location.href.split('#')[0];

      if (this.getQuery('code')) {
        this.$cookies.set('code', this.getQuery('code'));
        this.$cookies.set('state', this.getQuery('state'));
      }

      const code = this.$cookies.get('code');
      const appletId = this.$cookies.get('applet_id');
      if (!this.$store.state.code) {
        this.$store.commit('setCodeBack', {
          applet_id: appletId,
          code
        });
        _post('frontend/member/login', {
          code: this.getQuery('code'),
          applet_id: Number(this.getQuery('state'))
        })
          .then(res => {  // 登入获取session和openid
            console.log('login', res);
            const data = res.data.data;
            this.$cookies.set('openid', data.openid);
            this.$cookies.set('session', data.session);
            this.$store.commit('setApplet', {
              session: data.session,
              openid: data.openid
            });
            console.log('state', this.$store.state);
            return Promise.resolve(data);
          })
          .then(res => { // 获取微信配置
            this.getBanner();
            _post('frontend/applet/get_wxsdk_config', {
              url: domine,
              applet_id: 1,
              session: res.session,
              openid: res.openid
            }).then(res => {
              console.log('config', res);
              this.wxSet(res.data.data);
              // let url = `https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=${this.$store.state.openid}&lang=zh_CN`;
              // this.$axios.get(url).then(res => {
              //   console.log('userInfo', res);
              // });
            });
          });
      } else {
        this.getBanner();
        this.getLocation();
        if (this.$cookies.get('shop')) {
          this.shopList = JSON.parse(this.$cookies.get('shop'));
          console.log('shop-list', this.shopList);
        }
      }
    },
    methods: {
      getBanner() {
        _post('frontend/banner/index', {}).then(res => {
          let data = res.data.data;
          this.banners = data;
        });
      },
      goShop(item) {
        this.$store.commit('setShop', {shop: item});
        this.$router.push({name: 'Goods'});
      },

      getQuery: name => {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) {
          return unescape(r[2]);
        }
        return null;
      },
      getShops(res) {
        _post('frontend/shop/index', {
          session: this.$store.state.session,
          openid: this.$store.state.openid,
          applet_id: this.$store.state.applet_id,
          name: this.keyWords,
          latitude: res.latitude,
          longitude: res.longitude
        }).then(res => {
          const data = res.data.data;
          console.log('shop', data);

          if (res.data.code === 200) {
            this.shopList = data.shops;
            this.location = data.location;
            this.$cookies.set('shop', JSON.stringify(this.shopList));
          }
          console.log('list-', res);
        });
      },
      getLocation() {
        console.log('res', 'getlocal');
        this.keyWords = '';
        this.wx.ready(() => {
          console.log('wx.ready', this.wx);
          this.wx.getLocation({
            type: 'wgs84', // BD09
            success: res => {
              console.log(res);
              this.getShops(res);
            },
            cancel: function (res) {
              alert('用户拒绝授权获取地理位置');
              // that.getShopFjStudio();
            },
            fail: res => {
              console.log('loca_fail', res);
            }

          });
        });
      },
      wxSet(data) {
        this.wx.config({
          debug: false,
          appId: data.appId,
          timestamp: data.timestamp,
          nonceStr: data.nonceStr,
          signature: data.signature,
          jsApiList: ['checkJsApi', 'chooseImage', 'uploadImage', 'previewImage', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareTimeline', 'chooseWXPay', 'getLocation']
        });

        // 处理验证失败的信息
        this.wx.error(function (res) {
          console.log('验证失败返回的信息:', res);
        });

        this.wx.checkJsApi({
          jsApiList: ['getLocation'],
          success: function (res) {
            if (res.checkResult.getLocation === false) {
              alert('你的微信版本太低，不支持微信JS接口，请升级到最新的微信版本！');
              return;
            }
          }
        });
        this.getLocation();
      }
    }

  };
</script>


<style>
  .banner {
    width: 100%;
    height: 100%;
  }

  /*<!-- head -->*/
  .search input {
    border-radius: 50px;
    background: #F5F5F5;
  }

  .el-carousel__item h3 {
    color: #475669;
    font-size: 14px;
    opacity: 0.75;
    line-height: 150px;
    margin: 0;
  }

  /**/
  .rebtn {
    display: flex;
    justify-content: center;
    align-items: center;
    background: rgb(198, 170, 118);
    border-radius: 10px;
    height: 50px;
    color: #fff;

  }

  /*店铺列表*/
  .store {
    display: flex;
    flex-flow: column;
    align-items: flex-start;
    justify-content: space-around;
    height: 80px;
    border-bottom: 1px solid #eee;
  }

  .store > div {
    width: 100%;
  }

  .store .name {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #2b333b;
    min-width: 50px;
    margin-left: 0;
  }

  .store .time {
  }

  .el-header {
    padding: 0;
  }

  .el-carousel__item:nth-child(2n) {
    background-color: #99a9bf;
  }

  .el-carousel__item:nth-child(2n+1) {
    background-color: #d3dce6;
  }

  /**/
  .el-row {
    margin-bottom: 20px;

  &
  :last-child {
    margin-bottom: 0;
  }

  }
  .el-col {
    border-radius: 4px;
  }

  .bg-purple-dark {
    background: #99a9bf;
  }

  .bg-purple {
    background: #d3dce6;
  }

  .bg-purple-light {
    background: #e5e9f2;
  }

  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }

  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }
</style>
